package com.itheima.service.login.impl;

import com.itheima.domain.UserInfo;
import com.itheima.factory.MapperFactory;
import com.itheima.mapper.login.LoginMapper;
import com.itheima.service.login.LoginService;
import com.itheima.utils.MD5Util;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * 用户 业务层 实现
 */
public class LoginServiceImpl implements LoginService {

    /**
     * 查询所有订单信息
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserInfo login(String username, String password) {

        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            LoginMapper mapper = MapperFactory.getMapper(sqlSession, LoginMapper.class);
            //调用Mapper层操作
            UserInfo user = mapper.findByUsernameAndPwd(username, password);
            //如果查询失败 看看是不是以邮箱登录的
            if (user == null) {
                user = mapper.findByEmailAndPwd(username, password);
            }

            if (user != null) {
                //判断开启停用状态
                String status = mapper.findStatus(user.getId());
                return status.equals("1") ? user : null;
            }
            return null;
        } catch (Exception e) {
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                //提交事务
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void updatePwd(String id, String newPwd) {
        SqlSession sqlSession = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            LoginMapper mapper = MapperFactory.getMapper(sqlSession, LoginMapper.class);
            //调用Mapper层操作
            mapper.updatePwd(id, newPwd);
            //提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                //提交事务
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
